package site.qjdb.service.impl;


import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import site.qjdb.dao.CartDao;
import site.qjdb.dao.OrderDao;
import site.qjdb.pojo.Cart;
import site.qjdb.pojo.Goods;
import site.qjdb.pojo.OrderItem;
import site.qjdb.pojo.Orders;
import site.qjdb.service.GoodsService;
import site.qjdb.service.OrderService;

import javax.annotation.Resource;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
	@Resource
	private OrderDao orderDao;
	@Resource
	private CartDao cartDao;
	@Resource
	private GoodsService goodsService;

	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
	public void addOrder(Orders orders,
						 List<OrderItem> orderItemList,
						 List<Cart> cartList,
						 List<Goods> goodsList) throws Exception {
		orderDao.addOrder(orders);
		// 给订单子项添加订单id
		for (int i = 0; i < orderItemList.size(); i++) {
			OrderItem orderItem = orderItemList.get(i);
			orderItem.setOid(orders.getOid());
		}
		orderDao.addOrderItem(orderItemList);
		// 在购物车中删除相关商品
		if(cartList != null && cartList.size() > 0) {
			if(cartList.size() == 1) {
				cartDao.updateCart(cartList.get(0));
			} else {
				cartDao.updateCarts(cartList);
			}
		}
		
		// 更改商品已预约数量和状态
		for(Goods _goods : goodsList) {
			goodsService.modifyGoods(_goods);
		}
	}

}
